/*
 * DA8.c
 *
 * Created: 5/7/2014 2:24:42 AM
 *  Author: Vincent
 */ 


#include "mcp4725.c"				//library for the MCP4725
#include <avr/io.h>		
#include <compat/deprecated.h>		//library for interrupt handling
#define F_CPU 1000000UL				//1Mhz clock
#include <util/delay.h>
#include <math.h>
#define PI 0.31415926;


void initADC(void)
{
	ADCSRA |= (1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2); //make ADC enable and select clk/128
	ADMUX |= (1<<REFS0)|(1<<ADLAR); // ADC Channel 0 Selected, data will be left justified with reference voltage same as VCC
}
uint16_t readADC3(void)
{
	//PC0(ADC0) should be 0(INPUT)
	ADCSRA |= (1<<ADSC);			//start conversion
	while((ADCSRA&(1<<ADIF))==0);	//wait for end of conversion
	return ADC;
}
void exec_delay(uint16_t delay)
{
	//vary sine wave, in increments of 10, controls frequency
	if (delay < 0b0000110011001100)
	_delay_us(1);
	else if (delay < 0b0010010010100100)
	_delay_us(2);
	else if (delay < 0b0100000000000000)
	_delay_us(3);
	else if (delay < 0b0101100110011001)
	_delay_us(4);
	else if (delay < 0b0111001100110011)
	_delay_us(5);
	else if (delay < 0b1000110011001100)
	_delay_us(6);
	else if (delay < 0b1010011001100110)
	_delay_us(7);
	else if (delay < 0b1100000000000000)
	_delay_us(8);
	else if (delay < 0b1101100110011001)
	_delay_us(9);
	else
	_delay_us(10);
}
int main(void)
{
	int res;
	DDRD  = 1<<PD1;
	PORTB = ~1<<PB1;
	DDRB  = 1<<PB5; // PORTB_5 as output error LED
	PORTB = ~(1<<PB5);
	DDRC  = 0x00;

	twi_init();
	initADC(); //initialize A2D conversion
	
	while(1)
	{
		uint16_t tempval = readADC3(); //read pot value, this data should range from 0 to 65,536 (16-bit)
		int max = 2 * PI;
		for (int deg=0; deg < max; deg++)
		{
			int tempData = 127+(127*sin(deg));	//result of sin will vary from +1 to -1
			res = twi_send(0xC0,tempData);
			if (res==0)
				sbi(PORTD,1);
			else
				cbi(PORTD,1);
			exec_delay(tempval); //execute delay control based on analog
		}
	}
}
